import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.List;

import javax.swing.tree.TreeNode;

/*
 * @lc app=leetcode.cn id=145 lang=java
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    //递归写法
    // public List<Integer> postorderTraversal(TreeNode root) {
    //     List<Integer> res=new ArrayList<>();
    //     postorder(root, res);
    //     return res;


    // }
    // public void postorder(TreeNode node,List<Integer> res){
    //     if(node==null){
    //         return;
    //     }
    //     postorder(node.left, res);
    //     postorder(node.right, res);
    //     res.add(node.val);
    // }
    public List<Integer> postorderTraversal(TreeNode root) {
        //非递归写法
        List<Integer> res=new ArrayList<>();
        if(root!=null){
            Deque<TreeNode> stack=new ArrayDeque<>();
            stack.push(root);
            while(!stack.isEmpty()){
                TreeNode node=stack.pop();
                res.add(node.val);
                if(node.left!=null){//左
                    stack.push(node.left);
                }
                if(node.right!=null){//右
                    stack.push(node.right);
                }
            }
        }
        //res此时是中右左，反转后就是左右中
        Collections.reverse(res);
        return res;
    }
}
// @lc code=end

